package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tanhua.domain.db.PageResult;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mg.Comment;
import com.tanhua.domain.vo.AcceptMessageVo;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mg.MessagesApi;
import com.tanhua.server.utils.GetAgeUtil;
import com.tanhua.server.utils.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessagesService {

    //订阅动态消息管理服务接口
    @Reference
    private MessagesApi messagesApi;
    //订阅用户详细信息服务接口
    @Reference
    private UserInfoApi userInfoApi;
    //注入TheadLocalUtils对象
    @Autowired
    private ThreadLocalUtils threadLocalUtils;

    /**
     * 点赞列表、评论列表、喜欢列表
     */
    public PageResult<AcceptMessageVo> likeMessage(Long page, Long pagesize, Integer type) {
        //a.获取当前用户的id
        Long currentUserId = threadLocalUtils.getUserId();
        //b.根据当前用户id和评论类型（动态、视频、评论）查询信息 返回分页数据pageResult<Comment>
        PageResult<Comment> commentPageResult = messagesApi.findUserIdByPublishIdAndType(page, pagesize, type, currentUserId);
        //c.创建一个PageResult<AcceptMessageVo>对象
        PageResult<AcceptMessageVo> voPageResult = new PageResult<>();
        //e.创建一个存储AcceptMessageVo的集合对象
        ArrayList<AcceptMessageVo> voArrayList = new ArrayList<>();
        //d.判断commentPageResult.getItems对象是否为null
        List<Comment> items = commentPageResult.getItems();
        if (CollectionUtils.isNotEmpty(items)) {
            //e.如果不为null 那么就遍历
            for (Comment comment : items) {
                AcceptMessageVo acceptMessageVo = new AcceptMessageVo();
                //f.得到每个comment对象的userId---评论的用户id
                Long commentUserId = comment.getUserId();
                //g.根据userId查询userInfo表 得到用户的详细信息
                UserInfo userInfo = userInfoApi.findUserInfoByID(commentUserId);
                //h.将详细信息封装给AcceptMessageVo
                BeanUtils.copyProperties(userInfo, acceptMessageVo);
                //i.单独赋值id
                acceptMessageVo.setId(String.valueOf(userInfo.getId()));
                acceptMessageVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                //j.将vo对象添加到集合pageResult<AcceptMessageVo>.items
                voArrayList.add(acceptMessageVo);
            }
            //k.赋值pageResult对象
            BeanUtils.copyProperties(commentPageResult, voPageResult);
            //设置集合
            voPageResult.setItems(voArrayList);
        }
        //返回
        return voPageResult;
    }

}
